<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class RaoVat extends UserBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->library('mypaging');
        $this->load->model('repo/raovat_model', 'raovat_model');
    }

    private function intialPaging($user_id, $option=array()) {
        $this->mypaging->setCount($this->raovat_model->shopCountRaoVat($user_id, $option));
        $this->mypaging->setLimit(RAO_VAT_LIMIT);
        $this->mypaging->setMainURL(mns_rao_vat_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex = 1) {
        $option = array();
        $f = $this->input->get('f', true);
        if($f!==false && $f=='trash'){
            $option = array(
                'a.active_flg'=>0,
                'a.deleted_at'=>NULL
                );
        }
        $aData = array();
        $this->intialPaging($this->user_id, $option);
        $offset = ($pageIndex - 1) * RAO_VAT_LIMIT;
        $aRaoVat = $this->raovat_model->shopPaging($this->user_id, RAO_VAT_LIMIT, $offset, array(), $option);
        $aData['pagingBar'] = $this->mypaging->getBar($pageIndex, array('f'=>$f));
        $aData['pageTitle'] = 'Rao vặt';
        $aData['aRaoVat'] = $aRaoVat;
        $this->renderView('backend/shop/raovat/index', $aData);
    }

    public function get($slug) {
        $this->load->helper('file');
        $aSelect = array(
            'a.id, a.title',
            'a.slug',
            'a.image',
            'a.cate_id',
            'a.place_id',
            'a.description',
            'a.detail',
            'a.active_flg',
            'a.deleted_at',
            'c.image_folder');
        $raoVat = $this->raovat_model->getSingleBySlug($slug, $aSelect);
        if ($raoVat == null || count($raoVat) == 0) {
            show_404();
        }
        $raoVatPlace = $this->raovat_model->getRaoVatPlace();

        $this->load->model('repo/category_model', 'cate_model');
        $raoVatCate = $this->cate_model->getCategories();

        $aData = array(
            'pageTitle'    => $raoVat->getTitle(),
            'oRaoVat'      => $raoVat,
            'aRaoVatPlace' => $raoVatPlace,
            'aRaoVatCate'  => $raoVatCate,
            'action'       => 'update',
            'action_link'  => mns_page_url(RAOVAT_SLUG . '/cap-nhat')
            );
        $this->renderView('backend/shop/raovat/single', $aData);
    }

    public function insert() {
        $this->load->helper('file');
        $raoVat = new RaoVat_Entity();
        $raoVat->setTitle('Thêm mới');
        $raoVat->setActiveFlg(1);
        $raoVat->image_folder = $this->image_folder;
        $raoVatPlace = $this->raovat_model->getRaoVatPlace();
        $this->load->model('repo/category_model', 'cate_model');
        $raoVatCate = $this->cate_model->getCategories();
        $aData = array(
            'pageTitle' => 'Thêm mới',
            'oRaoVat' => $raoVat,
            'aRaoVatPlace' => $raoVatPlace,
            'aRaoVatCate' => $raoVatCate,
            'action' => 'insert',
            'action_link' => mns_page_url(RAOVAT_SLUG . '/them-moi'));
        $this->renderView('backend/shop/raovat/single', $aData);
    }

    public function doInsert() {
        $aResult = array();
        $raovat = $this->input->post('raovat', true);
        $raovat_detail = $this->input->post('raovat_detail');
        $this->form_validation->set_rules('raovat[title]', 'lang:raovat_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('raovat[slug]', 'lang:raovat_slug', 'trim|required|callback_slug_check|callback_slug_check_exist[raovat.slug]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aResult);
            return;
        }
        $date = new DateTime();
        $raovat['created_at'] = $date->format('Y-m-d H:i:s');
        $raovat['user_id'] = $this->user_id;

        //set image
        if(isset($raovat['image']) && $raovat['image']!=''){
            $aImage = explode('/', $raovat['image']);
            if(count($aImage)==2){
                if (strpos($raovat['image'], TEMP_FOLDER_URL) !== false) {
                    $this->load->library('MyImage', 'myimage');
                    $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, RAOVAT_IMAGE_URL, $aImage[1]);
                }
                $raovat['image'] = $aImage[1];
            } else {
                $raovat['image'] = null;
            }
        } else {
            $raovat['image'] = null;
        }
        $raovat['detail'] = $raovat_detail;


        $result = $this->raovat_model->insert($raovat);
        if (!$result) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul><li>' . $this->lang->line('system_error') . '</li></ul>'
                );
        } else {
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('insert_success'),
                'href' => mns_raovat_single_url($raovat['slug'])
                );
        }
        $this->renderJSON($aResult);
        return;
    }

    public function doUpdate() {
        $aResult = array();
        $raovat = $this->input->post('raovat', true);
        $raovat_detail = $this->input->post('raovat_detail');
        $raovat_id = $this->encrypt->decode($this->input->post('raovat_id'));
        if ($raovat_id == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('system_error') . '</li></ul>');
            $this->renderJSON($aResult);
            return;
        }
        $this->form_validation->set_rules('raovat[title]', 'lang:raovat_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('raovat[slug]', 'lang:raovat_slug', 'trim|required|callback_slug_check|callback_slug_update_check_exist[raovat.slug]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aResult);
            return;
        }

        if(!isset($raovat['active_flg'])){
            $raovat['active_flg'] = 0;
        }
        $date = new DateTime();
        if(!isset($raovat['delete_flg'])){
            $raovat['deleted_at'] = null;
            $raovat['updated_at'] = $date->format('Y-m-d H:i:s');
        } else {
            $raovat['deleted_at'] = $date->format('Y-m-d H:i:s');
            unset($raovat['delete_flg']);
        }

        //set image
        if(isset($raovat['image']) && $raovat['image']!=''){
            if (strpos($raovat['image'], TEMP_FOLDER_URL) !== false) {
                $image_name = explode('/', $raovat['image']);
                $image_name = $image_name[1];
                $this->load->library('MyImage', 'myimage');
                $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, RAOVAT_IMAGE_URL, $image_name);
                $raovat['image'] = $image_name;
            } else if(strpos($raovat['image'], RAOVAT_IMAGE_URL) !== false){
                $a = explode('/', $raovat['image']);
                if(count($a)==2){
                    $raovat['image'] = $a[1];
                } else {
                    $raovat['image'] = null;
                }
            } else {
                $raovat['image'] = null;
            }
        } else {
            $raovat['image'] = null;
        }

        $raovat['detail'] = $raovat_detail;
        $result = $this->raovat_model->update($raovat_id, $raovat);
        if (!$result) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('system_error') . '</li></ul>'
                );
        } else {
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success'),
                'href' => mns_raovat_single_url($raovat['slug'])
                );
        }
        $this->renderJSON($aResult);
        return;
    }

    public function flashUpdate() {
        $aResult = array();
        $date = new DateTime('now');
        $raovat = $this->input->post('raovat');
        //set id
        $raovat_id = $this->encrypt->decode($raovat['id']);
        if(!$raovat){
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error'),
                'text' => $this->lang->line('update_fail'));
            $this->renderJSON($aResult);
            return;
        }

        unset($raovat['id']);
        //set publish_flg
        if (isset($raovat['active_flg'])) {
            if($raovat['active_flg'] == 1){
                $raovat['active_flg'] = 1;
            } else {
                $raovat['active_flg'] = 0;
            }
            //set update_at
            $raovat['updated_at'] = $date->format(DATE_TIME_FORMAT);
        }

        //set deleted_at
        if (isset($raovat['delete_flg'])) {
            if($raovat['delete_flg'] == 1){
                $raovat['deleted_at'] = $date->format(DATE_TIME_FORMAT);
            } else {
                $raovat['deleted_at'] = NULL;
                $raovat['updated_at'] = $date->format(DATE_TIME_FORMAT);
            }
        }
        unset($raovat['delete_flg']);

        $result = $this->raovat_model->update($raovat_id, $raovat);
        if ($result) {
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success')
                );
        } else {
            $aResult = array(
                'code' => 0,
                'text' => $this->lang->line('system_error')
                );
        }

        $this->renderJSON($aResult);
    }

    public function slug_check_exist($str) {
        return $this->raovat_model->checkRaoVatExist($str);
    }

    public function slug_update_check_exist($str) {
        $id = $this->input->post('raovat_id');
        $id = $this->encrypt->decode($id);
        return $this->raovat_model->checkRaoVatExist($str, $id);
    }

    private function intialSearchPaging($search_key, $user_id) {
        $this->mypaging->setCount($this->raovat_model->shopSearchCountRaoVat($search_key, $user_id));
        $this->mypaging->setLimit(RAO_VAT_LIMIT);
        $this->mypaging->setMainURL(mns_rao_vat_search_paging_url());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function search($pageIndex=1){
        $search_key = $this->input->get('s', true);
        $aData = array();
        $this->intialSearchPaging($search_key, $this->user_id);
        $offset = ($pageIndex - 1) * RAO_VAT_LIMIT;
        $aRaoVat = $this->raovat_model->shopSearchPaging($search_key, $this->user_id, RAO_VAT_LIMIT, $offset);
        $aData['pageTitle'] = 'Rao vặt';
        $aData['pagingBar'] = $this->mypaging->getBar($pageIndex, array('s'=>$search_key));
        $aData['aRaoVat']   = $aRaoVat;
        $aData['searchkey'] = $search_key;
        $this->renderView('backend/shop/raovat/index', $aData);
    }
}
?>